<template>
  <div ref="chartRef"></div>
</template>

<script setup>
import { onMounted, ref, defineProps, toRefs } from 'vue';
import { Chart } from '@antv/g2';

const props = defineProps({ config: Object })
const { config } = toRefs(props)

const chartRef = ref();

const keys  = window.CONFIG.dataHeader

const initChart = () => {
const chart = new Chart({
  ...config.value,
  container: chartRef.value,
  autoFit: true,
  forceFit: true,
});

chart.coordinate({ type: 'theta', innerRadius: 0.2, outerRadius: 0.8 });

chart
  .title({
    title: `${window.CONFIG.systemName}分析`,
  })
  .interval()
  .data({
    type: 'fetch',
    value: '/api/hdfs/read-csv?path=/output/hdfsJobByMonth/part-r-00000',
    format: 'csv',
    autoType: true,
    transform: [
      {
        type: 'log'
      },
      {
        type: 'custom',
        callback: (data) => {
          const result = keys.map(key => {
            const re = data.reduce((currentSum, item) =>  currentSum + item[key] , 0)
            return { [window.CONFIG.chartX]: key, [window.CONFIG.chartY]: +(re.toFixed(2)) }
          })
          return result
        }
      },
      {
        type: 'sortBy',
        fields: [[window.CONFIG.chartY, false]]
      }
    ],

  })
  .transform({ type: 'stackY' })
  .encode('y', window.CONFIG.chartY)
  .encode('color', window.CONFIG.chartX)
  .legend('color', { position: 'bottom', layout: { justifyContent: 'center' } })
  .label({
    position: 'outside',
    text: (data) => `${data.type}: ${data.count}`,
  })
  .tooltip((data) => ({
    name: data.type,
    value: `${data.count}`,
  }));


  chart
  .text()
  .style('text', '')
  // Relative position
  .style('x', '50%')
  .style('y', '50%')
  .style('dy', -25)
  .style('fontSize', 34)
  .style('fill', '#8c8c8c')
  .style('textAlign', 'center');

  chart
  .text()
  .style('text', '')
  // Relative position
  .style('x', '50%')
  .style('y', '50%')
  .style('dx', -25)
  .style('dy', 25)
  .style('fontSize', 44)
  .style('fill', '#8c8c8c')
  .style('textAlign', 'center');

chart
  .text()
  .style('text', '')
  // Relative position
  .style('x', '50%')
  .style('y', '50%')
  .style('dx', 35)
  .style('dy', 25)
  .style('fontSize', 34)
  .style('fill', '#8c8c8c')
  .style('textAlign', 'center');


chart.render();
return chart;
}

onMounted(() => {
//   console.log(chartRef.value)
initChart()
})

</script>

<style scoped>

</style>